import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { editUser } from "@/api/user";

// export const updateUserInfoAsync = createAsyncThunk(
//   "user/updateUserInfoAsync",
//   async (payload, thunkAPI) => {
//     await editUser(payload.userId, payload.newInfo);
//     thunkAPI.dispatch(updateUserInfo(payload.newInfo));
//   }
// );

export const updateUserInfoAsync = createAsyncThunk("user/updateUserInfoAsync", async (payload) => {
  // 更新数据库信息
  await editUser(payload.userId, payload.newInfo);
  // 更新仓库信息
  return payload.newInfo;
});

export const userSlice = createSlice({
  name: "user",
  initialState: {
    isLogin: false,
    userInfo: {},
  },

  reducers: {
    initUserInfo: (state, { payload }) => {
      state.userInfo = payload;
    },

    changeLoginStatus: (state, { payload }) => {
      state.isLogin = payload;
    },

    clearUserInfo: (state) => {
      state.userInfo = {};
    },
    // 更新用户信息
    // updateUserInfo: (state, { payload }) => {
    //   for (let key in payload) {
    //     state.userInfo[key] = payload[key];
    //   }
    // },
  },
  extraReducers: (bulider) => {
    bulider.addCase(updateUserInfoAsync.fulfilled, (state, { payload }) => {
      for (let key in payload) {
        state.userInfo[key] = payload[key];
      }
    });
  },
});

export const { initUserInfo, changeLoginStatus, clearUserInfo, updateUserInfo } = userSlice.actions;
export default userSlice.reducer;
